package com.fingard.dsp.bank.directbank.bocz01;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextWriter;


public class BOCZ01Base extends DirectBase implements ITcpClient{
    private final static String CHANNEL = "LN";
    protected String sessionId = "";//会话编号 首次发送交易上送-1，后续交易上送首次交易产生的Id（可能用不到）
    protected String serviceId = "";//服务编号
    protected String serialNo = "";//交易流水号
    protected String signature = "";//签名数据


    /**
     *
     * @param xmlWriter  传送的xml报文
     * @throws Exception
     */
    protected void writeCommonHeader(XmlTextWriter xmlWriter) throws Exception {

    /*00000 sessionId|serviceId|customerId|userId|bsnCode|reqTime|serialNo|channel|certType|certNo|#交易请求XML包
          会话编号|服务编号|企业客户号|企业用户编号|业务编号|请求服务时间|交易流水号|渠道标示|企业证件类型|证件号
          报文长度5为前面补0+报文头+报文体
          企业客户号同企业用户编号*/

        if (StringHelper.isNullOrEmpty(serviceId)) {
            throw new Exception("未赋值serviceId");
        }
        //yyyyMMddHHmmss
        String reqTime = Format.DateTime14Format.format(new Date());
        xmlWriter.writeStartDocByDeclaration(serviceId+"|"+bankFront.loginName+"|"+bankFront.org+"|"+bankFront.operator+"|"+reqTime+"|"
                +serialNo+"|"+CHANNEL+"|"+getBankConfig().getValueAsString("certType")+"|"+getBankConfig().getValueAsString("certNo")+
                "|#<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        xmlWriter.writeStartElement("BankData");
        xmlWriter.writeStartElement("opReq");
    }

    protected String[] sendToBank(String p_reqStr) throws Exception {

        String[] retStr = new String[]{"",""};

        WriteBankLogLn("1.提交银行的地址：" + bankFront.serverURL + ":" + bankFront.serverPort);

        //发送银行前置
        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverURL,Integer.parseInt(bankFront.serverPort),this);
        p_reqStr = p_reqStr+"<sign>"+signature+"</sign>";
        String tmpCharset = "GBK";
        int length = p_reqStr.getBytes(tmpCharset).length;
        //在上送报文前添加报文长度5位数字，不足五位左补‘0’
        p_reqStr = String.format("%05d",length)+""+p_reqStr;
        System.out.println(p_reqStr);
        byte[] tmpBytesBody = p_reqStr.getBytes(tmpCharset);

        WriteBankLogStep2(p_reqStr);
        TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpBytesBody);
        retStr[0] = tmpReceiver.connState;
        if(tmpReceiver.recBytes != null){
            retStr[1] = new String(tmpReceiver.recBytes,0, tmpReceiver.readedLength, tmpCharset);
            WriteBankLogStep3(retStr[1]);
        }
        else{
            retStr[1] = tmpReceiver.getConnMsg();
        }
        if(!tmpReceiver.isCompleted){
            WriteBankLogLn(tmpReceiver.getConnMsg());
        }
        return retStr;
    }
    // 发送签名地址TCP/IP协议传送
    protected String[] sendToBankSignXml(String signXml) throws Exception{
        String[] retStr = new String[]{"",""};

        WriteBankLogLn(bankFront.serverIP+":"+bankFront.signPort);

        //发送银行前置
        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP,Integer.parseInt(bankFront.signPort),this);
        String tmpCharset = getCharset();
        int length = signXml.getBytes(tmpCharset).length;
        String qmhead = "POST HTTP://192.168.10.206/servlet/ABC95599.Trans HTTP/1.0\r\n" +
                "Accept:image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*\r\n" +
                "Referer: HTTP://192.168.10.206/personRACrtLY.htm\r\n" +
                "Accept-Language: zh-cn\r\n" +
                "Content-Type: INFOSEC_SIGN/1.0\r\n" +
                "Proxy-Connection: Keep-Alive\r\n" +
                "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)\r\n" +
                "Host: 192.168.10.206\r\n" +
                "Content-Length: "+String.valueOf(length)+"\r\n" +
                "Pragma: no-cache\r\n\r\n";
        String p_reqString = qmhead+signXml;
        System.out.println(p_reqString);
        byte[] tmpBytesBody = p_reqString.getBytes(tmpCharset);
        WriteBankLogStep2(p_reqString);
        TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpBytesBody);
        retStr[0] = tmpReceiver.connState;
        if(tmpReceiver.recBytes != null){
            retStr[1] = new String(tmpReceiver.recBytes,0, tmpReceiver.readedLength, tmpCharset);
            WriteBankLogStep3(retStr[1]);
        }
        else{
            retStr[1] = tmpReceiver.getConnMsg();
        }
        if(!tmpReceiver.isCompleted){
            WriteBankLogLn(tmpReceiver.getConnMsg());
        }
        WriteBankLogLn("4.签名返回的结果：" + retStr[1]);
        return retStr;
    }

    //清除报文数据的空格和换行符
    protected  static String clearLineWrapAndBlank(String xml){
        return xml.replace("\r","").replace("\n","").replace(" ","");
    }
    protected static boolean isActiveRetCode(String retCode) {
        if (retCode != null) {
            if (retCode.equals("000000")) {
                return true;
            }
        }
        return false;
    }

    protected String getCharset(){
        return getBankConfig().getCharset("GBK");
    }

    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            String tmpCharset = "GBK";
            String tmpRecNow = new String(p_receiver.recBytes,0, p_receiver.readedLength, tmpCharset);
            if(tmpRecNow.indexOf("</BankData>") >= 0){
                p_receiver.contentLength = p_receiver.readedLength;
                p_receiver.contentStartIndex = 0;
            }
        }
    }
}
